package com.example.auth.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.auth.entity.SysUser;
import com.example.auth.entity.dto.LoginDTO;
import com.example.auth.mapper.SysUserMapper;
import com.example.auth.service.SysUserService;
import com.example.auth.utils.JwtHelper;
import com.example.auth.utils.RedisUtil;
import com.example.auth.utils.ResponseUtil;
import com.example.auth.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 李某人
 * @Date 2023/7/22 23:16
 * @Version 1.0
 */
public class TokenLoginFilter  extends UsernamePasswordAuthenticationFilter {

    private RedisUtil redisUtil;

    private SysUserMapper sysUserMapper;

    public TokenLoginFilter(AuthenticationManager authenticationManager,RedisUtil redisUtil,SysUserMapper sysUserMapper) {
        this.setAuthenticationManager(authenticationManager);
        this.setPostOnly(false);
        //指定登录接口及提交方式，可以指定任意路径
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/system/admin/login","POST"));
        this.redisUtil = redisUtil;
        this.sysUserMapper = sysUserMapper;
    }

    /**
     * 登录认证
     * @param req
     * @param res
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {
        try {
            LoginDTO loginDTO = new ObjectMapper().readValue(req.getInputStream(), LoginDTO.class);
            Authentication authenticationToken = new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword());

            return this.getAuthenticationManager().authenticate(authenticationToken);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 登录成功
     * @param request
     * @param response
     * @param chain
     * @param auth
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
        User user = (User) auth.getPrincipal();
        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, user.getUsername()));
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
        //保存权限
        redisUtil.set(sysUser.getUsername(), JSON.toJSONString(user.getAuthorities()));
        redisUtil.set(token,sysUser,30 * 60);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        ResponseUtil.out(response, Result.success(map));
    }

    /**
     * 登录失败
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException e) throws IOException, ServletException {

        if(e instanceof BadCredentialsException) {
            ResponseUtil.out(response, Result.fail( e.getMessage()));
        }
        ResponseUtil.out(response, Result.fail( e.getMessage()));
    }
}
